using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RBAC.ErrorCode;
using RBAC.Write.Api.Application.Command.ERP.PurchasingManagement.RawMaterialSuppliers;
using RBAC.Write.Api.Application.Command.ERP.PurchasingManagement.PurchaseOrders;
using RBAC.Write.Api.Application.Command.ERP.PurchasingManagement.PurchaseArrivalNotes;
using RBAC.Write.Api.Application.Command.ERP.PurchasingManagement.PurchaseInvoicefolder;
using RBAC.Write.Api.Application.Command.ERP.PurchasingManagement.PurchaseReturns;
using System.IO;

namespace RBAC.Write.Api.Controllers.ERP
{
    /// <summary>
    /// 采购管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PurchasingManagementController : ControllerBase
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<PurchasingManagementController> _logger;
        ///<summary>
        /// 中介者
        /// </summary>
        private readonly IMediator _mediator;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志</param>
        /// <param name="mediator">中介者</param>
        public PurchasingManagementController(ILogger<PurchasingManagementController> logger, IMediator mediator)
        {
            _logger = logger;
            _mediator = mediator;
        }


        /// <summary>
        /// 添加供应商
        /// </summary>
        /// <param name="request">添加供应商命令</param>
        /// <returns>返回影响行数</returns>
        [HttpPost]
        public async Task<APIResult<int>> AddRawMaterialSupplier(AddRawMaterialSupplierCommand request)
        {
            
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 修改供应商
        /// </summary>
        /// <param name="request">修改供应商命令</param>
        /// <returns>返回影响行数</returns>
        [HttpPut]
        public async Task<APIResult<int>> UpdateRawMaterialSupplier(UpdateRawMaterialSupplierCommand request)
        {
            return await _mediator.Send(request);
        }
        /// <summary>
        /// 逻辑删除供应商（启用状态禁止删除）
        /// </summary>
        /// <param name="request">删除命令</param>
        /// <returns>返回影响行数</returns>
        [HttpDelete]
        public async Task<APIResult<int>> DeleteRawMaterialSupplier([FromBody] DeleteRawMaterialSupplierCommand request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 新增采购发票
        /// </summary>
        /// <param name="request">新增采购发票命令</param>
        /// <returns>返回新增的主键ID</returns>
        [HttpPost]
        public async Task<APIResult<int>> AddPurchaseInvoice([FromBody] AddPurchaseInvoiceCommands request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 新增采购退货单
        /// </summary>
        /// <param name="request">新增采购退货单命令</param>
        /// <returns>返回新增记录ID</returns>
        [HttpPost]
        public async Task<APIResult<int>> AddPurchaseReturn([FromBody] AddPurchaseReturnCommands request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 导入供应商信息（Excel）
        /// </summary>
        /// <param name="file">上传的Excel文件(.xlsx/.xls)</param>
        /// <param name="hasHeader">首行是否为表头，默认true</param>
        /// <returns>成功导入的行数</returns>
        [HttpPost]
        [Consumes("multipart/form-data")]
        public async Task<APIResult<int>> ImportRawMaterialSuppliers([FromForm] ImportRawMaterialSuppliersForm form)
        {
            if (form == null || form.File == null || form.File.Length == 0)
            {
                return new APIResult<int> { Code = APIEnums.Fail, Msg = "文件为空", Data = 0 };
            }

            await using var ms = new MemoryStream();
            await form.File.CopyToAsync(ms);
            var cmd = new ImportRawMaterialSuppliersCommand
            {
                FileName = form.File.FileName,
                FileBytes = ms.ToArray(),
                HasHeader = form.HasHeader
            };
            return await _mediator.Send(cmd);
        }

        /// <summary>
        /// 新增采购订单
        /// </summary>
        /// <param name="request">新增采购订单命令</param>
        /// <returns>返回新记录ID</returns>
        [HttpPost]
        public async Task<APIResult<int>> AddPurchaseOrder([FromBody] AddPurchaseOrderCommand request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 编辑采购订单（主表+可选重置明细）
        /// </summary>
        [HttpPut]
        public Task<APIResult<int>> UpdatePurchaseOrder([FromBody] UpdatePurchaseOrderCommand request)
        {
            return _mediator.Send(request);
        }

        /// <summary>
        /// 上传采购订单附件（任意格式，无需表单ID）
        /// </summary>
        [HttpPost]
        [Consumes("multipart/form-data")]
        public async Task<APIResult<string>> UploadPurchaseOrderAttachment([FromForm] UploadPurchaseOrderAttachmentForm form)
        {
            if (form == null || form.File == null || form.File.Length == 0)
            {
                return new APIResult<string> { Code = APIEnums.Fail, Msg = "文件为空", Data = string.Empty };
            }

            await using var ms = new MemoryStream();
            await form.File.CopyToAsync(ms);
            var cmd = new UploadPurchaseOrderAttachmentCommand
            {
                FileName = form.File.FileName,
                FileBytes = ms.ToArray(),
                ContentType = form.File.ContentType
            };
            return await _mediator.Send(cmd);
        }

        /// <summary>
        /// 批量逻辑删除采购订单
        /// </summary>
        [HttpPut]
        public async Task<APIResult<int>> BatchDeletePurchaseOrders([FromBody] BatchDeletePurchaseOrdersCommand request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 批量修改采购订单单据状态（仅允许：开立 -> 审核 或 开立 -> 撤回）
        /// </summary>
        [HttpPut]
        public Task<APIResult<int>> BatchChangePurchaseOrderStatus([FromBody] BatchChangePurchaseOrderStatusCommand request)
        {
            return _mediator.Send(request);
        }

        /// <summary>
        /// 新增采购到货单（主表 + 明细）
        /// </summary>
        /// <param name="request">新增采购到货单命令</param>
        /// <returns>返回新增记录ID</returns>
        [HttpPost]
        public async Task<APIResult<int>> AddPurchaseArrivalNote([FromBody] AddPurchaseArrivalNoteCommand request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 编辑采购到货单（主表 + 可选重置明细）
        /// </summary>
        [HttpPut]
        public Task<APIResult<int>> UpdatePurchaseArrivalNote([FromBody] UpdatePurchaseArrivalNoteCommand request)
        {
            return _mediator.Send(request);
        }

        /// <summary>
        /// 批量逻辑删除采购到货单
        /// </summary>
        [HttpPut]
        public Task<APIResult<int>> BatchDeletePurchaseArrivalNotes([FromBody] BatchDeletePurchaseArrivalNotesCommand request)
        {
            return _mediator.Send(request);
        }

        /// <summary>
        /// 批量修改采购到货单单据状态（仅允许：开立 -> 审核 或 开立 -> 撤销）
        /// </summary>
        [HttpPut]
        public Task<APIResult<int>> BatchChangePurchaseArrivalNoteStatus([FromBody] BatchChangePurchaseArrivalNoteStatusCommand request)
        {
            return _mediator.Send(request);
        }

    }
    
}
